package com.campus.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.domain.po.Course;
import com.campus.service.CourseService;
import com.campus.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/course")
public class CourseController {

    @Autowired
    private CourseService courseService;

    @PreAuthorize("hasAnyRole('ADMIN', 'TEACHER')")

    @PostMapping("/create")
    public R createCourse(@RequestBody Course course) {
        Course createdCourse = courseService.createCourse(course);
        return R.success(createdCourse);
    }

    @PreAuthorize("hasAnyRole('ADMIN', 'TEACHER')")
    @DeleteMapping("/delete/{id}")
    public R deleteCourse(@PathVariable Integer id) {
        boolean removed = courseService.deleteCourseById(id);
        return removed ? R.success(200) : R.error(500, "Failed to delete course");
    }

    @PreAuthorize("hasAnyRole('ADMIN', 'TEACHER')")
    @PutMapping("/update")
    public R updateCourse(@RequestBody Course course) {
        Course updatedCourse = courseService.updateCourse(course);
        return updatedCourse != null ? R.success(updatedCourse) : R.error(500, "Failed to update course");
    }
    @PreAuthorize("hasAnyRole('ADMIN', 'TEACHER')")
    @GetMapping("/get/{id}")
    public R getCourse(@PathVariable Integer id) {
        Course course = courseService.getCourseById(id);
        return course != null ? R.success(course) : R.error(500, "Course not found");
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/list")
    public R getCourseList(
            @RequestParam(required = false) String courseName,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        if (courseName != null && !courseName.isEmpty()) {
            wrapper.like("course_name", courseName); // 模糊查询课程名称
        }
        return R.success(courseService.page(new Page<>(page, size), wrapper).getRecords());
    }
}
